﻿using System.Collections.Concurrent;
using WebSocketApi.Interface;

namespace WebSocketApi.Services
{
    public class NoticeCacheManager : INoticeCacheManager
    {

        /*
         * 1、消息已经发出，没有接收对象上线时，需要缓存，待上线后发出
         * 2、消息发送失败、网络连接问题或Socket服务状态异常。
         */
        private static readonly ConcurrentDictionary<string, List<object>> Notices = new ConcurrentDictionary<string, List<object>>();

        /// <summary>
        /// 获取当前用户所有离线消息
        /// </summary>
        /// <returns></returns>
        public List<object> GetUserAllHistoryNotices(string toUser)
        {
            var noticeList = Notices[toUser];
            return noticeList;
        }

        /// <summary>
        /// 缓存离线消息:离线消息Key的格式由调用方处理
        /// </summary>
        /// <param name="toUser">接收人</param>
        /// <param name="message"></param>
        public void AddNotice(string toUser, object message)
        {
            var oldNoticeList = GetUserAllHistoryNotices(toUser);
            var newNoticeList = oldNoticeList;
            oldNoticeList.Add(message);
            Notices.TryUpdate(toUser, newNoticeList, oldNoticeList);
        }

        /// <summary>
        /// 保存消息发送记录
        /// </summary>
        /// <param name="toUser"></param>
        /// <param name="message"></param>
        public void AddNoticeRecord(string toUser, object message)
        {
            var cacheKey = $"NoticesHistory:{toUser}";
            var oldNoticeList = GetUserAllHistoryNotices(cacheKey);
            var newNoticeList = oldNoticeList;
            oldNoticeList.Add(message);
            Notices.TryUpdate(toUser, newNoticeList, oldNoticeList);
        }

        /// <summary>
        /// 删除缓存中的消息
        /// </summary>
        /// <param name="toUser"></param>
        public void RemoveNotice(string toUser)
        {
            var noticeList = new List<object>();
            Notices.TryRemove(toUser, out noticeList);

        }
    }
}